package com.hwadee.backend.service;

import com.hwadee.backend.entity.*;
import com.hwadee.backend.entity.HealthRecord.*;
import com.hwadee.backend.mapper.HealthRecordMapper;
import com.hwadee.backend.mapper.UserRecordMapper;
import com.hwadee.backend.util.HealthRecordConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hwadee.backend.entity.BatchHealthRecordRequest;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HealthRecordService {
    private static final Logger logger = LoggerFactory.getLogger(HealthRecordService.class);
    @Autowired
    private UserRecordMapper userRecordMapper;
    @Autowired
    private HealthRecordMapper healthRecordMapper;

    public List<AllergyHistory> getAllergyHistory(int userId) {
        try {
            // 第一步：通过 userId 查询 user_record 表获取所有相关的 UserRecord 记录
            List<UserRecord> userRecords = userRecordMapper.selectByUserId(userId);
            if (userRecords.isEmpty()) {
                return List.of();
            }

            List<HealthRecord> allHealthRecords = new ArrayList<>();
            String recordType = "过敏史";

            // 遍历所有 UserRecord 记录，获取对应的健康记录
            for (UserRecord userRecord : userRecords) {
                int recordId = userRecord.getRecordId();
                List<HealthRecord> healthRecords = healthRecordMapper.selectByRecordIdAndType(recordId, recordType);
                allHealthRecords.addAll(healthRecords);
            }

            // 转换为 AllergyHistory 对象
            return allHealthRecords.stream()
                    .map(HealthRecordConverter::convert)
                    .filter(AllergyHistory.class::isInstance)
                    .map(AllergyHistory.class::cast)
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            return List.of();
        }
    }

    public List<FamilyHistory> getFamilyHistory(int userId) {
        try {
            // 第一步：通过 userId 查询 user_record 表获取所有相关的 UserRecord 记录
            List<UserRecord> userRecords = userRecordMapper.selectByUserId(userId);
            if (userRecords.isEmpty()) {
                return List.of();
            }

            List<HealthRecord> allHealthRecords = new ArrayList<>();
            String recordType = "家族病史";

            // 遍历所有 UserRecord 记录，获取对应的健康记录
            for (UserRecord userRecord : userRecords) {
                int recordId = userRecord.getRecordId();
                List<HealthRecord> healthRecords = healthRecordMapper.selectByRecordIdAndType(recordId, recordType);
                allHealthRecords.addAll(healthRecords);
            }

            // 转换为 FamilyHistory 对象
            return allHealthRecords.stream()
                    .map(HealthRecordConverter::convert)
                    .filter(FamilyHistory.class::isInstance)
                    .map(FamilyHistory.class::cast)
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            return List.of();
        }
    }

    public List<HealthIndicators> getHealthIndicators(int userId) {
        try {
            // 第一步：通过 userId 查询 user_record 表获取所有相关的 UserRecord 记录
            List<UserRecord> userRecords = userRecordMapper.selectByUserId(userId);
            if (userRecords.isEmpty()) {
                return List.of();
            }

            List<HealthRecord> allHealthRecords = new ArrayList<>();
            String recordType = "健康指标";

            // 遍历所有 UserRecord 记录，获取对应的健康记录
            for (UserRecord userRecord : userRecords) {
                int recordId = userRecord.getRecordId();
                List<HealthRecord> healthRecords = healthRecordMapper.selectByRecordIdAndType(recordId, recordType);
                allHealthRecords.addAll(healthRecords);
            }

            // 转换为 HealthIndicators 对象
            return allHealthRecords.stream()
                    .map(HealthRecordConverter::convert)
                    .filter(HealthIndicators.class::isInstance)
                    .map(HealthIndicators.class::cast)
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            return List.of();
        }
    }

    public List<MedicalExamReport> getMedicalExamReport(int userId) {
        try {
            // 第一步：通过 userId 查询 user_record 表获取所有相关的 UserRecord 记录
            List<UserRecord> userRecords = userRecordMapper.selectByUserId(userId);
            if (userRecords.isEmpty()) {
                return List.of();
            }

            List<HealthRecord> allHealthRecords = new ArrayList<>();
            String recordType = "体检报告";

            // 遍历所有 UserRecord 记录，获取对应的健康记录
            for (UserRecord userRecord : userRecords) {
                int recordId = userRecord.getRecordId();
                List<HealthRecord> healthRecords = healthRecordMapper.selectByRecordIdAndType(recordId, recordType);
                allHealthRecords.addAll(healthRecords);
            }

            // 转换为 MedicalExamReport 对象
            return allHealthRecords.stream()
                    .map(HealthRecordConverter::convert)
                    .filter(MedicalExamReport.class::isInstance)
                    .map(MedicalExamReport.class::cast)
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            return List.of();
        }
    }

    public List<MedicationRecord> getMedicationRecord(int userId) {
        try {
            // 第一步：通过 userId 查询 user_record 表获取所有相关的 UserRecord 记录
            List<UserRecord> userRecords = userRecordMapper.selectByUserId(userId);
            if (userRecords.isEmpty()) {
                return List.of();
            }

            List<HealthRecord> allHealthRecords = new ArrayList<>();
            String recordType = "用药记录";
            
            // 遍历所有 UserRecord 记录，获取对应的健康记录
            for (UserRecord userRecord : userRecords) {
                int recordId = userRecord.getRecordId();
                List<HealthRecord> healthRecords = healthRecordMapper.selectByRecordIdAndType(recordId, recordType);
                allHealthRecords.addAll(healthRecords);
            }
            // 转换为 MedicationRecord 对象
            List<MedicationRecord> medicationRecords = allHealthRecords.stream()
                    .map(HealthRecordConverter::convert)
                    .filter(MedicationRecord.class::isInstance)
                    .map(MedicationRecord.class::cast)
                    .collect(Collectors.toList());
            // 输出转换后得到的用药记录数量，并打印每条用药记录的具体属性
            logger.info("用户 ID 为 {} 的健康记录转换后得到 {} 条用药记录", userId, medicationRecords.size());
//            medicationRecords.forEach(record -> {
//                logger.info("用药记录详情 - 用药原因: {}, 药品名称: {}, 用法用量: {}, 用药结果: {}, 药物副作用: {}, 备注: {}",
//                        record.getMedicationReason(), record.getMedicationName(), record.getUsageAndDosage(),
//                        record.getMedicationResult(), record.getDrugSideEffects(), record.getRemarks());
//            });
            
            return medicationRecords;
        } catch (Exception e) {
            return List.of();
        }
    }

    public List<PastMedicalHistory> getPastMedicalHistory(int userId) {
        try {
            // 第一步：通过 userId 查询 user_record 表获取所有相关的 UserRecord 记录
            List<UserRecord> userRecords = userRecordMapper.selectByUserId(userId);
            if (userRecords.isEmpty()) {
                return List.of();
            }

            List<HealthRecord> allHealthRecords = new ArrayList<>();
            String recordType = "既往病史";

            // 遍历所有 UserRecord 记录，获取对应的健康记录
            for (UserRecord userRecord : userRecords) {
                int recordId = userRecord.getRecordId();
                List<HealthRecord> healthRecords = healthRecordMapper.selectByRecordIdAndType(recordId, recordType);
                allHealthRecords.addAll(healthRecords);
            }

            // 转换为 PastMedicalHistory 对象
            return allHealthRecords.stream()
                    .map(HealthRecordConverter::convert)
                    .filter(PastMedicalHistory.class::isInstance)
                    .map(PastMedicalHistory.class::cast)
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            return List.of();
        }
    }

    // 新增方法，在新增健康记录时同步插入 user_record 记录
    public int addHealthRecord(HealthRecord healthRecord, int id) {
        UserRecord userRecord = new UserRecord();
        userRecord.setId(id);
        // 插入 user_record 表并获取自动生成的 recordId
        int result = userRecordMapper.insert(userRecord);
        if (result > 0) {
            // 这里获取自增的 recordId
            int generatedRecordId = userRecord.getRecordId();
            logger.info("插入 user_record 表成功，生成的 recordId: {}", generatedRecordId);
            healthRecord.setRecordId(generatedRecordId);
            int insertResult = healthRecordMapper.insert(healthRecord);
            if (insertResult > 0) {
                return generatedRecordId;
            }
        }
        return 0;
    }

    public int deleteHealthRecord(int recordId) {
        int result = healthRecordMapper.deleteById(recordId);
        if (result > 0) {
            return userRecordMapper.deleteById(recordId);
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateHealthRecord(HealthRecord healthRecord) {
        try {
            logger.info("开始更新健康记录，记录 ID: {}", healthRecord.getRecordId());
            logger.info("更新记录内容: {}", healthRecord);
            int result = healthRecordMapper.updateById(healthRecord);
            logger.info("更新影响行数: {}", result);
            if (result > 0) {
                logger.info("健康记录更新成功，记录 ID: {}", healthRecord.getRecordId());
            } else {
                logger.warn("健康记录更新失败，未找到对应记录或数据未变化，记录 ID: {}", healthRecord.getRecordId());
            }
            return result;
        } catch (Exception e) {
            logger.error("健康记录更新失败，记录 ID: {}", healthRecord.getRecordId(), e);
            throw e; // 抛出异常触发事务回滚
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean batchInsertHealthRecords(BatchHealthRecordRequest request) {
        int userId = request.getUserId();
        List<HealthRecord> healthRecords = request.getHealthRecords();
        
        try {
            for (HealthRecord healthRecord : healthRecords) {
                UserRecord userRecord = new UserRecord();
                userRecord.setId(userId);
                
                // 插入 user_record 表并获取自动生成的 recordId
                int userRecordResult = userRecordMapper.insert(userRecord);
                if (userRecordResult > 0) {
                    int generatedRecordId = userRecord.getRecordId();
                    healthRecord.setRecordId(generatedRecordId);
                    
                    // 插入 health_record 表
                    int healthRecordResult = healthRecordMapper.insert(healthRecord);
                    if (healthRecordResult <= 0) {
                        throw new RuntimeException("插入健康记录失败");
                    }
                } else {
                    throw new RuntimeException("插入用户记录失败");
                }
            }
            return true;
        } catch (Exception e) {
            logger.error("批量插入健康记录失败", e);
            throw e; // 抛出异常触发事务回滚
        }
    }
}
